package com.leejxx.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leejxx.model.common.dto.ResponseResult;
import com.leejxx.model.common.enums.AppHttpCodeEnum;
import com.leejxx.model.user.dtos.LoginDto;
import com.leejxx.model.user.pojos.ApUser;
import com.leejxx.user.dao.ApUserDao;
import com.leejxx.user.service.ApUserLoginService;
import com.leejxx.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author LeeJx
 * @ClassName ApUserLoginServiceImpl
 * @Description TODO
 * @date 2021/3/2 18:58
 * @Version 1.0
 */
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    private ApUserDao apUserDao;

    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验参数
        if (dto.getEquipmentId() == null && StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.手机号+密码登录
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())) {
            //2.1.查询用户
            ApUser apUser = apUserDao.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }

            //2.2.比对密码
            String salt = apUser.getSalt();
            String password = dto.getPassword();
            password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (password.equals(apUser.getPassword())) {
                //2.3.返回jwt
                Map<String, Object> map = new HashMap();
                map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                apUser.setPassword("");
                apUser.setSalt("");
                map.put("user", apUser);
                return ResponseResult.okResult(map);

            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            //3.设备登录
            if(dto.getEquipmentId() == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
